<?php
// including this file will ensure that the database schema matches the current code.
//
global $database;

function version1(){
  global $database;
  $tableName = "users";
  $database->query("update $tableName set password = md5(password)");
  $tableName = "config";
  $database->query("update $tableName set password = md5(password)");
  $tableName = "config_seller";
  $database->query("update $tableName set password = md5(password)");

}
function version2(){
  global $database;
  $tableName = "locations";
  $database->query("update $tableName set password = md5(password)");

}
function version3(){
  global $database;
  $tableName = "users";
  $database->query("ALTER TABLE $tableName ADD activation_time DATETIME DEFAULT '0000-00-00 00:00:00'");

}

function doVersion($currentVersionNumber, $thisVersionNumber){
  global $database;
  if ($currentVersionNumber >= $thisVersionNumber) {
    return $currentVersionNumber;
  }

  
  $database->startTransaction();
  try {

    // use 'variable functions' to figure out which function to call.
    $code = "version$thisVersionNumber";
    $code();
    $database->commitTransaction();

  } catch (exception $e){
    $database->rollbackTransaction();
    error_log($e);
  }  
  error_log("database upgraded to version $thisVersionNumber.");
  return $thisVersionNumber; 
}

// setup
$version ="0";
$result = $database->select("select value from options where name = 'dbversion'");
if ($result) { 
  $version = $result[0]['value'];
} else {
  // first time dbversion option is used, add it
  $query = "insert into options (name, value) values ('dbversion','0')";
  error_log("inserting option: $query");
  $database->query($query);
}

$startVersion = $version;
// do upgrades, if needed
// could add some logic here to require a new file for each release
$version = doVersion($version, 1);
$version = doVersion($version, 2);
$version = doVersion($version, 3);

// update version if needed
if ($startVersion != $version) {
  $database->query("update options set value = '$version' where name = 'dbversion'"); 
}

?>
